<template>
  <div v-loading="tableLoading" class="vip-detail-balance-record">
    <!-- 卡片 -->
    <div class="balance-card">
      <el-row :gutter="10">
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_1" />
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_2" />
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_3" />
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="app-main-content-box">
      <!-- 筛选 -->
      <div class="filter">
        <!-- 筛选 -->
        <div class="app-main-filter-collapse-box filter">
          <el-collapse>
            <el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
              <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
                <el-form-item label="选择时间：" prop="date">
                  <!-- :rules="[
                  { required: true, message: '时间区间不能为空'}
                  ]"-->
                  <el-date-picker
                    v-model="filterForm.date"
                    type="datetimerange"
                    range-separator="~"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="['00:00:00', '23:59:59']"
                  />
                </el-form-item>
                <el-form-item label="业务单号：" prop="bizOrderNo">
                  <el-input
                    v-model="filterForm.bizOrderNo"
                    placeholder="请输入业务单号"
                    style="width:400px;"
                  />
                </el-form-item>
                <el-form-item label="门店：" prop="shopId">
                  <el-select
                    v-model="filterForm.shopId"
                    filterable
                    placeholder="可通过名称搜索"
                    style="width:400px"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.user.allManageShopFilterOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="终端：" prop="deviceId">
                  <el-select
                    v-model="filterForm.deviceId"
                    filterable
                    placeholder="可通过终端名/终端编号搜索"
                    style="width:400px"
                  >
                    <template v-for="item in $store.state.user.allManageDeviceFilterOptions">
                      <el-option
                        v-if="filterForm.shopId === '' ||item.shopId == filterForm.shopId || item.kdDeviceNo ==''"
                        :key="item.id"
                        :label="
                          item.kdDeviceNo === ''
                            ? item.deviceName
                            : item.deviceName + '(' + item.kdDeviceNo + ')'
                        "
                        :value="item.kdDeviceNo"
                      />
                    </template>
                  </el-select>
                </el-form-item>
                <el-form-item label="变动类型：" prop="recordTypes">
                  <el-checkbox
                    v-model="checkAllRecordTypes"
                    :indeterminate="isIndeterminateRecordTypes"
                    class="fl check-all"
                    @change="handlecheckAllRecordTypesChange"
                  >全选</el-checkbox>
                  <el-checkbox-group
                    v-model="filterForm.recordTypes"
                    @change="handleCheckRecordTypesChange"
                  >
                    <el-checkbox
                      v-for="(item,index) in recordTypesCheckOptions"
                      :key="index"
                      :label="item.value"
                    >{{ item.label }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="业务类型：" prop="bizCode">
                  <el-radio-group v-model="filterForm.bizCode">
                    <el-radio label="all">全部</el-radio>
                    <el-radio
                      v-for="(item,index) in manageBizCodeOptions"
                      :key="index"
                      :label="item.key"
                    >{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="业务来源：" prop="sourceCode">
                  <el-radio-group v-model="filterForm.sourceCode">
                    <el-radio label="all">全部</el-radio>
                    <template v-for="(item, index) in sourceCodeOptions">
                      <el-radio :key="index" :label="item.key">{{ item.label }}</el-radio>
                    </template>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="支付方式：" prop="payment">
                  <el-radio-group v-model="filterForm.payment">
                    <el-radio label="all">全部</el-radio>
                    <el-radio
                      v-for="item in paymentOptions"
                      :key="item.key"
                      :label="item.key"
                    >{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item class="filter-btn">
                  <el-button type="primary" round @click="submitForm('filterForm')">查 询</el-button>
                  <el-button round @click="resetForm('filterForm')">重 置</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <!-- 列表 -->
      <div class="balance-table">
        <el-table size="small" :data="list" stripe border style="width: 100%" empty-text="暂无数据">
          <el-table-column prop="time" label="变动时间" fixed="left" width="150" />
          <el-table-column prop="bizOrderNo" label="业务单号" fixed="left" width="150" />
          <el-table-column prop="recordType" label="变动类型" />
          <el-table-column prop="bizName" label="业务类型" />
          <el-table-column prop="sourceName" label="业务来源" />
          <el-table-column prop="payment" label="支付方式" />
          <el-table-column prop="balance" label="变动金额(元)">
            <template slot-scope="scope">
              <div v-if="Number(scope.row.balance)==0">{{ Number(scope.row.balance) }}</div>
              <div
                v-else
                :class="scope.row.balance>0?'app-text-color-danger':'app-text-color-success'"
              >{{ scope.row.balance>0?'+'+scope.row.balance:scope.row.balance }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="remainBalance" label="变动后总余额(元)" />
          <el-table-column prop="shopName" label="门店">
            <template slot-scope="scope">
              <span>{{ scope.row.shopName?scope.row.shopName:"总部" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="device" label="消费终端" />
          <el-table-column prop="operator" label="操作人" />
          <el-table-column prop="promoter" label="推广人" />
          <el-table-column prop="remark" label="业务备注" />
        </el-table>
        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total!==0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getVipAccountInfo } from '@/api/vip'
import {
  getBalanceRecordsList,
  getBalanceRecordStatistic
} from '@/api/statement'
// 组件
import ThreePointCard from './ThreePointCard'
export default {
  components: {
    ThreePointCard
  },
  props: {
    activeName: {
      type: String,
      require: true
    },
    vipDetail: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        // 分页配置
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      recordTypesCheckOptions: [
        {
          label: '充值',
          value: 1
        },
        {
          label: '赠送',
          value: 2
        },
        {
          label: '消费',
          value: 3
        },
        {
          label: '退款',
          value: 4
        },
        {
          label: '扣除',
          value: 5
        }
      ],
      recordTypesOptions: [1, 2, 3, 4, 5],
      // 状态
      tableLoading: false, // 表格loading
      checkAllRecordTypes: true, // recordType 多选状态
      isIndeterminateRecordTypes: false, // recordType
      // 数据
      cardData_1: ['总余额', 0, '累计获得', 0, '累计消费', 0, '冻结金额', 0],
      cardData_2: ['实充余额', 0, '累计充值', 0, '累计消费', 0, '冻结金额', 0],
      cardData_3: ['赠送余额', 0, '累计赠送', 0, '累计消费', 0, '冻结金额', 0],
      filterForm: {
        date: [],
        shopId: '',
        recordTypes: [1, 2, 3, 4, 5],
        bizOrderNo: '',
        deviceId: '',
        bizCode: 'all',
        sourceCode: 'all',
        payment: 'all'
      },
      list: [] // 表格数据
    }
  },
  computed: {
    ...mapGetters([
      'manageBizCodeOptions',
      'sourceCodeOptions',
      'paymentOptions'
    ]),
    shopId() {
      return this.filterForm.shopId
    }
  },
  watch: {
    activeName(val) {
      if (val === 'balance') {
        this.fetchData()
      }
    },
    shopId(newValue, oldValue) {
      this.filterForm.deviceId = ''
    }
  },
  mounted() {
    this.$store.dispatch('GetManageDevice') // 获取终端
  },
  methods: {
    /**
       *  获取数据
       */
    // 获取数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          // 请求数据
          const params = await this.setRequestParams()
          params.pageNum = page
          params.pageSize = pageSize
          const statisticParams = {}
          statisticParams.memberId = params.memberId
          this.tableLoading = true
          Promise.all([
            this.getTotal(statisticParams),
            this.getRecord(params)
          ]).then(() => {
            this.tableLoading = false
          })
        }
      })
    },

    // 获取请求筛选数据
    setRequestParams() {
      return new Promise((resolve, reject) => {
        const params = Object.assign({}, this.filterForm)
        params.beginTimestamp = params.date
          ? this.$momentMini(params.date[0]).unix()
          : ''
        params.endTimestamp = params.date
          ? this.$momentMini(params.date[1]).unix()
          : ''
        delete params.date
        params.memberId = this.vipDetail.member.id
        // 清除多余字段
        for (const key in params) {
          if (params[key] === '' || params[key] === 'all') {
            delete params[key]
          }
        }
        resolve(params)
      })
    },

    // 获取统计
    getTotal(statisticParams) {
      return new Promise((resolve, reject) => {
        getVipAccountInfo(statisticParams)
          .then((res) => {
            this.setCardTotal(res.data)
          })
          .catch((err) => {})
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取记录
    getRecord(params) {
      if (params.bizOrderNo) {
        delete params.beginTimestamp
        delete params.endTimestamp
      }
      return new Promise((resolve, reject) => {
        getBalanceRecordsList(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .catch((err) => {})
          .finally(() => {
            resolve()
          })
      })
    },

    setCardTotal(data) {
      // 赋值卡片一  总
      this.cardData_1.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.totalBalance)
      ) // 余额
      this.cardData_1.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.totalSumRecharge)
      ) // 累计获得
      this.cardData_1.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.totalSumConsume)
      ) // 累计消费
      this.cardData_1.splice(
        7,
        1,
        this.$options.filters.parseNumberToThousands(data.totalFrozen)
      ) // 冻结金额
      // 赋值卡片二 实充
      this.cardData_2.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.realBalance)
      ) // 实充余额
      this.cardData_2.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.realSumRecharge)
      ) // 累计充值
      this.cardData_2.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.realSumConsume)
      ) // 累计消费
      this.cardData_2.splice(
        7,
        1,
        this.$options.filters.parseNumberToThousands(data.realFrozen)
      ) // 冻结金额
      // 赋值卡片三 赠送
      this.cardData_3.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.givenBalance)
      ) // 赠送余额
      this.cardData_3.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.givenSumRecharge)
      ) // 累计赠送
      this.cardData_3.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.givenSumConsume)
      ) // 累计消费
      this.cardData_3.splice(
        7,
        1,
        this.$options.filters.parseNumberToThousands(data.givenFrozen)
      ) // 冻结金额
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
       * 按钮
       */
    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.checkAllRecordTypes = true // recordType 多选状态
      this.isIndeterminateRecordTypes = false // recordType
    },

    /**
       * 状态
       */
    // checkAllRecordType多选状态
    handlecheckAllRecordTypesChange(val) {
      if (val) {
        this.filterForm.recordTypes = this.recordTypesOptions
        this.checkAllRecordTypes = true
      } else {
        this.filterForm.recordTypes = []
        this.checkAllRecordTypes = false
      }
      this.isIndeterminateRecordTypes = false
    },

    handleCheckRecordTypesChange(value) {
      const checkedLength = value.length
      const maxLength = this.recordTypesOptions.length
      this.checkAllRecordTypes = checkedLength === maxLength
      this.isIndeterminateRecordTypes =
          checkedLength > 0 && checkedLength < maxLength
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .vip-detail-balance-record {
    /* 卡片 */
    .balance-card {
      .app-main-content-box {
        margin-bottom: 10px;
      }
    }
    /* 重置多选左边距 */
    .el-checkbox + .el-checkbox {
      margin-left: 0;
    }
    .el-checkbox {
      margin-right: 10px;
    }
  }

  /* 筛选 */
  .filter {
    .filter-btn {
      margin-bottom: 20px;
    }
    .check-all {
      margin-right: 30px;
    }
    .el-select {
      width: 120px;
    }
    .input-with-select {
      width: 400px;
    }
    // 换行
    .el-radio + .el-radio {
      margin-left: 0;
    }
    .el-radio {
      margin-right: 10px;
      height: 32px;
      line-height: 32px;
    }
  }
</style>
